<?php
/**
 * APP版本号.
 * User: xwc
 * Date: 2024/01/15
 */

namespace App\Model\Core\Sys;

use App\Model\CoreModel;

class AppVersionModel extends CoreModel
{
    protected string $table = 'app_version';

    const APP_PLATFORM_ANDROID = 'android';//平台信息，安卓
    public static array $app_platform = [
        self::APP_PLATFORM_ANDROID => 'android',
    ];

    /**
     * 添加一条信息
     * @param array $data
     * @return false|int
     */
    public function addOne(array $data): bool|int
    {
        if (empty($data)) {
            return false;
        }
        $res = $this->getConnectionTable()->insertGetId($data);
        if ($res) {
            $this->clearCache($data);
        }
        return $res;
    }

    /**
     * 清空缓存
     * @param array $item
     * @return $this
     */
    public function clearCache(array $item): static
    {
        $cache_k = $item['app_platform'];
        self::cleanCache($cache_k);
        return $this;
    }

    /**
     * 更新一条信息
     * @param int $id
     * @param array $data
     * @return bool|int
     */
    public function updateOne(int $id, array $data): bool|int
    {
        if ($id <= 0 || empty($data)) {
            return false;
        }
        $info = $this->getOne($id);
        if (empty($info)) {
            return false;
        }
        $res = $this->getConnectionTable()->where('id', $id)->update($data);
        if ($res) {
            $this->clearCache($info);
        }
        return $res;
    }

    /**
     * 根据ID获取单条信息
     * @param int $id
     * @return array
     */
    public function getOne(int $id): array
    {
        if ($id <= 0) return [];
        return obj_to_array($this->getConnectionTable()->where('id', $id)->first());
    }

    /**
     * 删除一条信息
     * @param int $id
     * @return bool|int
     */
    public function deleteOne(int $id): bool|int
    {
        if ($id <= 0) {
            return false;
        }
        $info = $this->getOne($id);
        if (empty($info)) {
            return false;
        }
        $res = $this->getConnectionTable()->where('id', $id)->delete();
        if ($res) {
            $this->clearCache($info);
        }
        return $res;
    }

    /**
     * 根据平台信息获取最后一条记录
     * @param string $app_platform
     * @param bool $is_cache
     * @return array
     */
    public function getLastOne(string $app_platform, bool $is_cache = true): array
    {
        if (empty($app_platform)) {
            return [];
        }
        return $this->cache($app_platform, function () use ($app_platform) {
            return obj_to_array($this->getConnectionTable()->where('app_platform', $app_platform)->orderBy('id', 'desc')
                ->first());
        }, $is_cache);
    }
}
